# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

# 如果想使用管道的话，那么就必须在settings中开启管道
class ScrapyDangdangPipeline:
    # item就是yield后面的book对象
    # w模式，会每一个对象都打开一次文件覆盖之前内容
    # 在爬虫文件开始之前就执行的方法
    def open_spider(self,spider):
        self.fp = open('book.json','w',encoding='utf-8')

    def process_item(self, item, spider):
        # write的对象必须是str
        self.fp.write(str(item))
        return item
    # 在爬虫文件执行结束后，执行的方法

    def close_spider(self,spider):
        self.fp.close()

# 多条管道开启
# 1.定义管道类
# 2.在settings中开启管道
import urllib.request
class DangDangDownloadPipeline:
    def process_item(self, item, spider):
        url = 'http:'+item.get('src')
        filename = './books/'+item.get('name')+'.jpg'
        urllib.request.urlretrieve(url=url,filename=filename)
        return item